﻿using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Web;
using log4net;
using GONES.Tools.Common;

namespace GONES.Tools.Web.HttpHandlers
{
    public class FileHandler : IHttpHandler
    {
        #region IHttpHandler Members

        protected static readonly
            ILog Log =
                LogManager.GetLogger("GONES.Tools");

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string file = context.Server.MapPath(context.Request.FilePath);
            Log.Info(file);
            try
            {


                if (File.Exists(file))
                {
                    context.Response.WriteFile(file);
                }
                else
                {
                    var client = new WebClient();
                    string url = GlobalSettings.Instance.FileServerUrl +
                                 ("/" + context.Request.FilePath).Replace("/" + context.Request.ApplicationPath, "");

                    if (Log.IsInfoEnabled)
                    {
                        Log.Info("path:" + url);
                    }

                    try
                    {
                        int index = file.LastIndexOf(".") + 1;
                        string extension = file.Substring(index).ToUpperInvariant();
                        if (string.Compare(extension, "JPG") == 0)
                            context.Response.ContentType = "image/jpeg";
                        else
                            context.Response.ContentType = "image/" + extension;
                        context.Response.BinaryWrite(client.DownloadData(url));
                    }
                    catch (Exception ex)
                    {
                        if (Log.IsErrorEnabled)
                            Log.Error(ex);
                    }
                }

            }
            catch (Exception exception)
            {
                Log.Error(exception.ToString());

            }
        }

        #endregion
    }
}